<template>
  <AdminLayout>
    <!-- 后台客户案例管理主容器 -->
    <div>
      <h1>案例管理</h1>
      <!-- 新增案例表单 -->
      <el-form :model="form" ref="formRef" label-width="80px" style="margin-bottom: 20px;">
        <el-form-item label="名称">
          <el-input v-model="form.title" placeholder="请输入案例名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" placeholder="请输入案例描述" />
        </el-form-item>
        <el-form-item label="行业">
          <el-input v-model="form.industry" placeholder="请输入所属行业" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">{{ form._id ? '更新' : '新增' }}</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 案例列表表格 -->
      <el-table :data="cases" style="width: 100%">
        <el-table-column prop="title" label="案例名称" width="200" />
        <el-table-column prop="description" label="案例描述" />
        <el-table-column prop="industry" label="所属行业" width="120" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="onEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="onDelete(scope.row._id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </AdminLayout>
</template>

<script setup>
import AdminLayout from '~/components/AdminLayout.vue'
import { ref, onMounted } from 'vue'
const cases = ref([])
const form = ref({ title: '', description: '', industry: '' })
const formRef = ref(null)

async function fetchCases() {
  const res = await fetch('/api/cases')
  cases.value = await res.json()
}

async function onSubmit() {
  if (form.value._id) {
    await fetch('/api/cases', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form.value)
    })
  } else {
    await fetch('/api/cases', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form.value)
    })
  }
  await fetchCases()
  onReset()
}

function onEdit(row) {
  form.value = { ...row }
}

async function onDelete(id) {
  await fetch(`/api/cases?id=${id}`, { method: 'DELETE' })
  await fetchCases()
}

function onReset() {
  form.value = { title: '', description: '', industry: '' }
  if (formRef.value) formRef.value.clearValidate && formRef.value.clearValidate()
}

onMounted(fetchCases)
</script>

<style scoped>
h1 {
  margin-bottom: 20px;
}
</style> 